<template>
  <div class="dialog-add-user-contain">
    <el-dialog
      :visible.sync="dialogVisible"
      :title="field"
      width="1200px"
      @close="handleClose"
      custom-class="dialog-search-form"
    >
      <el-collapse-transition>
        <card-search v-if="searchCardShow">
          <el-form ref="ruleForm" label-width="100px" class="dialog-ruleForm">
            <el-form-item label="手机号码:">
              <el-input
                v-model="phonenumber"
                clearable
                style="width: 180px"
                @change="initTable"
              />
            </el-form-item>
            <el-form-item label-width="0px">
              <div style="display: flex">
                <el-button
                  class="btn-search"
                  round
                  icon="el-icon-search"
                  size="medium"
                  @click="initTable"
                  >搜索</el-button
                >
                <el-button
                  class="btn-search"
                  round
                  icon="el-icon-refresh"
                  size="medium"
                  @click="resetTable"
                  >重置</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </card-search>
      </el-collapse-transition>
      <card-table>
        <div class="card-table-header">
          <div class="card-table-header-btns">
            <el-button
              class="btn-search"
              size="small"
              icon="el-icon-plus"
              @click="handleClick(null, 'add')"
              >添加用户</el-button
            >
            <el-button
              class="btn-search"
              size="small"
              icon="el-icon-close"
              :disabled="btnDisabled"
              @click="handleClick(null, 'cancel')"
              >批量取消授权</el-button
            >

            <el-input
              v-model="loginName"
              placeholder="请输入登录名称"
              style="width: 450px; margin-left: 10px"
              clearable
              size="small"
              @change="initTable"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="initTable"
              ></el-button>
            </el-input>
          </div>
          <div class="card-table-header-actions">
            <table-action
              :table-header="tableHeader"
              :search-show="true"
              @check-change="handleCheckChange"
              @search-click="handleSearchClick"
              @init-click="handleInitClick"
            />
          </div>
        </div>
        <el-table
          :data="tableData"
          max-height="400"
          border
          style="width: 100%"
          size="small"
          align="center"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#eff3f8', color: '#333' }"
          stripe
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="item in tableHeader"
            v-if="item.visible"
            :key="item.prop"
            :label="item.title"
            :min-width="item.width"
            :prop="item.prop"
            :sortable="item.sortble"
            :show-overflow-tooltip="true"
            :align="item.align"
          >
            <template #default="scope">
              <span v-if="item.prop === 'status'">{{
                scope.row[item.prop] == "0" ? "正常" : "停用"
              }}</span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
        </el-table>
        <XyPagination
          :total="total"
          :pageSizeNum="pageSize"
          :pageNum="currentPage"
          @pagination="handlerPagination"
        ></XyPagination>
      </card-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <AddUser
      v-model="dialogAddUserVisible"
      field="选泽用户"
      :roleId="rowData.roleId"
      @close="onClose"
    />
  </div>
</template>

<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import AddUser from "./AddUser.vue";
import XyPagination from "@/components/XyPagination";
import { allocatedList, cancelAuthUser } from "@/api/systemmanagement.js";
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    field: {
      type: String,
      default: "",
    },
    rowData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  components: {
    CardSearch,
    CardTable,
    TableAction,
    AddUser,
    XyPagination,
  },

  data() {
    return {
      searchCardShow: false,
      dialogAddUserVisible: false,
      btnDisabled: true,
      loginName: "",
      phonenumber: "",
      tableHeader: [
        {
          title: "登录名称",
          prop: "loginName",
          width: "150",
          align: "center",
          visible: true,
          sortble: false,
        },
        {
          title: "用户名称",
          prop: "userName",
          width: "150",
          align: "center",
          visible: true,
          sortble: true,
        },
        {
          title: "邮箱",
          prop: "email",
          width: "150",
          align: "center",
          visible: true,
          sortble: true,
        },
        {
          title: "手机",
          prop: "phonenumber",
          width: "150",
          align: "center",
          visible: true,
          sortble: true,
        },
        {
          title: "用户状态",
          prop: "status",
          width: "100",
          align: "center",
          visible: true,
          sortble: true,
        },
        {
          title: "创建时间",
          prop: "createTime",
          width: "200",
          align: "center",
          visible: true,
          sortble: true,
        },
      ],
      tableData: [],
      currentPage: 1,
      multipleSelection: [],
      pageSize: 20,
      total: 0,
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value; // 返回父组件通过 v-model 传递的值
      },
      set(val) {
        (this.loginName = ""), (this.phonenumber = ""), (this.pageNum = 1);
        this.pageSize = 20;
        this.searchCardShow = false;
        this.$emit("close", val); // 当 dialogVisible 变化时，通知父组件更新
      },
    },
  },
  watch: {
    collapse(val) {
      // 当 collapse 值变化时，控制所有节点展开或折叠
      this.handleCollapseChange(val);
    },
    checked(val) {
      // 新增: 监听 checked 值变化
      this.handleCheckedChange(val);
    },
    rowData: {
      handler(val) {
        if (val.roleId) {
          this.initTable();
        }
      },
    },
    value(val) {
      this.initTable();
    },
  },
  methods: {
    initTable() {
      let data = {
        roleId: this.rowData.roleId,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        loginName: this.loginName,
        phonenumber: this.phonenumber,
      };
      allocatedList(data).then((res) => {
        if (res.code == 0) {
          this.tableData = res.rows;
          this.total = res.total;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleClose() {
      this.dialogVisible = false; // 关闭弹窗
      this.$emit("close"); // 发送关闭事件给父组件
    },
    handleClick(row, field) {
      switch (field) {
        case "add":
          this.dialogAddUserVisible = true;
          this.loginName = "";
          this.phonenumber = "";
          break;
        case "cancel":
          this.$confirm(
            `确认取消选中的${this.multipleSelection.length}个用户授权吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            let data = {
              roleId: this.rowData.roleId,
              userIds: this.multipleSelection.map((item) => item.userId),
            };
            cancelAuthUser(data).then((res) => {
              if (res.code == 0) {
                this.$message.success("取消授权成功");
                this.initTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          });
          break;
        default:
          break;
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
    },
    resetTable() {
      this.phonenumber = "";
      this.initTable();
    },
    onClose() {
      this.initTable();
      this.dialogAddUserVisible = false;
    },
  },
};
</script>
<style lang="scss">
.dialog-add-user-contain {
  .dialog-ruleForm {
    width: 100%;
    display: flex;
    line-height: 60px;
    margin: 0 auto;
    .el-form-item {
      border: 0;
      .el-input__inner {
        border: 1px solid #e1e1e1 !important;
        width: 100%;
      }
    }
  }
  .el-card {
    margin: 15px;
  }
}
</style>
